package com.xmim.fulcrum.codec;


import com.xmim.fulcrum.FulcrumCodec;

import java.io.*;

public class JDKCodec implements FulcrumCodec {
    @Override
    public <T> byte[] encode(T object) {
        try {
            final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            final ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(object);
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> T decode(byte[] data, Class<T> clazz) {
        try {
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
            final ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return (T) objectInputStream.readObject();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
